package myky.com.doctorapp.fragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.github.nukc.stateview.Constant;
import com.gyf.barlibrary.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import net.lucode.hackware.magicindicator.FragmentContainerHelper;
import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import myky.com.doctorapp.R;
import myky.com.doctorapp.adapter.DoctorInfoViewPagerAdapter;
import myky.com.doctorapp.adapter.HomeExpertAdapter;
import myky.com.doctorapp.entity.BannerEntity;
import myky.com.doctorapp.entity.CaseCountsEntity;
import myky.com.doctorapp.entity.NewCaseListEntity;
import myky.com.doctorapp.entity.RecDoctorListEntity;
import myky.com.doctorapp.entity.TagListEntity;
import myky.com.doctorapp.base.BaseFragment;
import myky.com.doctorapp.base.CMApplication;
import myky.com.doctorapp.contract.HomeFragmentContract;
import myky.com.doctorapp.entity.PageEntity;
import myky.com.doctorapp.presenter.HomeFragmentPresenter;
import myky.com.doctorapp.ui.DoctorListActivity;
import myky.com.doctorapp.ui.FindDocotrHomePageActivity;
import myky.com.doctorapp.ui.MainActivity;
import myky.com.doctorapp.ui.SearchActivity;
import myky.com.doctorapp.utils.AppBarStateChangeListener;
import myky.com.doctorapp.ui.RemoteDoctorListActivity;
import myky.com.doctorapp.utils.BannerImageLoader;
import myky.com.doctorapp.utils.Constants;
import myky.com.doctorapp.utils.GallerySnapHelper;
import myky.com.doctorapp.utils.ToastUtils;
import myky.com.doctorapp.utils.SpanUtils;
import myky.com.doctorapp.wight.SpaceItemDecoration;


/**
 * @author Mr.li
 */
public class HomeFragment extends BaseFragment<HomeFragmentPresenter, List<BannerEntity.PayLoadBean.AdvertListBean>> implements HomeFragmentContract.View, BaseQuickAdapter.OnItemChildClickListener {

    @BindView(R.id.tablayout_holder)
    MagicIndicator magicIndicator;
    Unbinder unbinder;
    @BindView(R.id.viewpager)
    ViewPager infoViewPager;
    @BindView(R.id.collapsingToolbar)
    CollapsingToolbarLayout collapsingToolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.youthBanner)
    Banner youthBanner;
    @BindView(R.id.expertTextView)
    TextView expertTextView;
    @BindView(R.id.wenzhenTextView)
    TextView wenzhenTextView;
    @BindView(R.id.menzhenTextView)
    TextView menzhenTextView;
    @BindView(R.id.bingliTextView)
    TextView bingliTextView;
    @BindView(R.id.findDocText)
    TextView findDocText;
    @BindView(R.id.numberUpLoader)
    TextView numberUpLoader;
    @BindView(R.id.titleLayout)
    LinearLayout titleLayout;
    @BindView(R.id.smarRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.homeExpertListView)
    RecyclerView homeExpertListView;
    private List<String> imageUrls = new ArrayList<>();
    private List<RecDoctorListEntity.DataBean.PositionsBean> stringList_doctor;
    private List<TagListEntity.PayLoadBean.TagListBean> tagList;
    private MainActivity mainActivity;
    HomeExpertAdapter homeExpertAdapter;
    private AppBarStateChangeListener.State appbarState;
    @BindView(R.id.toTopLayout)
    RelativeLayout toTopLayout;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void hahaha(Message m) {

        int what = m.what;
        if (what == Constant.HOMESCROLL) {

            if (appbarState == AppBarStateChangeListener.State.COLLAPSED) {
                appbar.setExpanded(true);
                Message message = new Message();
                message.what = Constant.SCROLLTOFIST;
                EventBus.getDefault().post(message);
            }

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        if(unbinder!=null){
            unbinder.unbind();
        }
    }

    public HomeFragment() {

    }

    public static HomeFragment newInstance() {
        Bundle args = new Bundle();
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public HomeFragmentPresenter getPresenter() {
        return new HomeFragmentPresenter();
    }


    @Override
    protected void doRetry() {

        mPresenter.getBanner();
        mPresenter.getRecDoctorList("v1.0", "4", "1", "0");
        mPresenter.getTagList("0", "9");
        mPresenter.getCaseCounts();

    }

    @Override
    protected int injectTarget() {
        return R.id.smarRefreshLayout;
    }

    @Override
    public void unRegisterSomething() {
        super.unRegisterSomething();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mPresenter.getBanner();
        mPresenter.getRecDoctorList("v1.0", "4", "1", "0");
        mPresenter.getTagList("0", "9");
        mPresenter.getCaseCounts();
        smartRefreshLayout.setEnableLoadMore(false);
        stringList_doctor = new ArrayList<>();
        homeExpertListView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        homeExpertListView.addItemDecoration(new SpaceItemDecoration(20));
        ImmersionBar.with(this).titleBar(toolbar).init();
        homeExpertAdapter = new HomeExpertAdapter(stringList_doctor);
        homeExpertListView.setAdapter(homeExpertAdapter);
        homeExpertAdapter.setOnItemChildClickListener(this);
        GallerySnapHelper mGallerySnapHelper = new GallerySnapHelper();
        mGallerySnapHelper.attachToRecyclerView(homeExpertListView);
        CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) appbar.getLayoutParams();
        AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) layoutParams.getBehavior();

        

        if (behavior != null) {
            behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
                @Override
                public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
                    return true;
                }
            });
        }

        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {


            mPresenter.getBanner();
            mPresenter.getRecDoctorList("v1.0", "4", "1", "0");
            mPresenter.getTagList("0", "9");
            mPresenter.getCaseCounts();
            refreshLayout.finishRefresh(2000);
        });
        appbar.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {

                appbarState = state;

                if (state == State.COLLAPSED) {
                    smartRefreshLayout.setEnabled(false);
                } else if (state == State.EXPANDED) {
                    smartRefreshLayout.setEnabled(true);
                }
            }

            @Override
            public void onAppBarLayoutVerticalOffsetChanged(int verticalOffset) {

                int totalScrollRange = appbar.getTotalScrollRange();

                if (Math.abs(verticalOffset) == totalScrollRange) {
                    toTopLayout.setVisibility(View.VISIBLE);
                } else {
                    toTopLayout.setVisibility(View.GONE);
                }

                int i1 = youthBanner.getBottom() - titleLayout.getBottom();
                int total = 0;
                total = Math.abs(verticalOffset) + total;

                if (total <= 0) {
                    //在顶部时完全透明
                    ImmersionBar.with(HomeFragment.this).statusBarDarkFont(false).init();
                    toolbar.setBackgroundColor(Color.argb(0, 242, 242, 242));
                } else if (total <= i1) {
                    //在滑动高度中时，设置透明度百分比（当前高度/总高度）
                    double d = (double) total / i1;
                    double alpha = (d * 255);
                    toolbar.setBackgroundColor(Color.argb((int) alpha, 242, 242, 242));
                } else { //滑出总高度 完全不透明
                    toolbar.setBackgroundColor(Color.argb(255, 242, 242, 242));

                    ImmersionBar.with(HomeFragment.this).statusBarDarkFont(true).init();
                }
            }
        });

    }


    private void initViewPage() {
        List<Fragment> fragments = new ArrayList<>();
        for (int x = 0; x < tagList.size(); x++) {
            int tagid = tagList.get(x).getTagid();
            String text = tagList.get(x).getText();
            if (TextUtils.equals(text, "医生讲堂")) {
                DoctorLectureSubFragment newDoctorArticalFragment = new DoctorLectureSubFragment();

                Bundle bundle=new Bundle();
                bundle.putInt(Constants.TAGID,tagid);
                newDoctorArticalFragment.setArguments(bundle);
                fragments.add(newDoctorArticalFragment);
            } else {
                HomeNewsSubFragment newsFragment = new HomeNewsSubFragment();

                Bundle bundle=new Bundle();
                bundle.putInt(Constants.TAGID,tagid);
                newsFragment.setArguments(bundle);

                fragments.add(newsFragment);
            }
        }


        magicIndicator.setBackgroundColor(Color.parseColor("#ffffff"));
        CommonNavigator commonNavigator = new CommonNavigator(getActivity());
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return tagList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorTransitionPagerTitleView(context);
                simplePagerTitleView.setNormalColor(Color.parseColor("#343434"));
                simplePagerTitleView.setSelectedColor(getResources().getColor(R.color.theme_app));
                simplePagerTitleView.setText(tagList.get(index).getText());
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        infoViewPager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                linePagerIndicator.setColors(getResources().getColor(R.color.theme_app));
                return linePagerIndicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        LinearLayout titleContainer = commonNavigator.getTitleContainer();
        titleContainer.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        titleContainer.setDividerDrawable(new ColorDrawable() {
            @Override
            public int getIntrinsicWidth() {
                return UIUtil.dip2px(getActivity(), 15);
            }
        });

        final FragmentContainerHelper fragmentContainerHelper = new FragmentContainerHelper(magicIndicator);
        fragmentContainerHelper.setInterpolator(new OvershootInterpolator(2.0f));
        fragmentContainerHelper.setDuration(300);
        infoViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                fragmentContainerHelper.handlePageSelected(position);
            }
        });


        DoctorInfoViewPagerAdapter newSubAdapter = new DoctorInfoViewPagerAdapter(getChildFragmentManager(), infoViewPager, fragments);

        infoViewPager.setAdapter(newSubAdapter);

        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, infoViewPager);

        newSubAdapter.onPageSelected(0);
    }

    @OnClick({R.id.haha, R.id.askToExpert, R.id.remoteInterrogation, R.id.outpatientAppointment, R.id.uploadTheCases, R.id.findDoctor, R.id.fragment_new_home_right, R.id.fragment_new_home_lin1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.askToExpert:
                startActivity(DoctorListActivity.class);
                break;
            case R.id.remoteInterrogation:
                startActivity(RemoteDoctorListActivity.class);
                break;
            case R.id.outpatientAppointment:
                ToastUtils.showAtCenter("点击首页预约门诊");
                break;
            case R.id.uploadTheCases:
                if (CMApplication.getInstance().isLoginOk()) {
                    mPresenter.getUserCaseList();
                } else {
                    ToastUtils.showAtCenter("未登录");
                }
                break;
            case R.id.findDoctor:
               startActivity(FindDocotrHomePageActivity.class);
                break;
            case R.id.fragment_new_home_lin1:
                startActivity(SearchActivity.class);
                break;
            case R.id.fragment_new_home_right:
                ToastUtils.showAtCenter("点击了首页消息");
                break;
            case R.id.haha:
                appbar.setExpanded(true);
                Message message = new Message();
                message.what = Constant.SCROLLTOFIST;
                EventBus.getDefault().post(message);
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
    }

    @Override
    public void showBannerList(List<BannerEntity.PayLoadBean.AdvertListBean> data) {
        //获取新的banner数据集合
        final List<BannerEntity.PayLoadBean.AdvertListBean> bannerList = data;
        if (bannerList != null) {
            List<String> imageList = new ArrayList<>();
            for (int i = 0; i < bannerList.size(); i++) {
                imageList.add(bannerList.get(i).getResource().get(0));
            }
            imageUrls.clear();
            imageUrls.addAll(imageList);
        }
        youthBanner.setImages(imageUrls).setImageLoader(new BannerImageLoader()).setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                .setIndicatorGravity(BannerConfig.RIGHT).setDelayTime(4000).start();
    }

    @Override
    public void showDataError(String errorMessage) {
        ToastUtils.showAtCenter(errorMessage);
    }

    @Override
    public void showDataSuccess(List<BannerEntity.PayLoadBean.AdvertListBean> datas) {

    }

    @Override
    public void showPages(PageEntity pageEntity) {

    }

    @Override
    public void showTagList(List<TagListEntity.PayLoadBean.TagListBean> taglist) {
        this.tagList = taglist;
        if (tagList != null) {
            initViewPage();
        }
    }

    @Override
    public void showRecDoctorList(List<RecDoctorListEntity.DataBean.PositionsBean> positionsList) {
        stringList_doctor.clear();
        stringList_doctor.addAll(positionsList);
        homeExpertAdapter.notifyDataSetChanged();
    }

    @Override
    public void showCaseCounts(CaseCountsEntity.PayLoadBean caseCounts) {
        int customNum = caseCounts.getTotalCustomerNum();
        int illnessNum = caseCounts.getTotalIllnesssNum();
        int addCustomNum = caseCounts.getTodayAddCustomerNum();
        int addIllnessNum = caseCounts.getTodayAddIllnesssNum();
        int totalCustomNum = customNum + addCustomNum;
        int totalIllnessNum = illnessNum + addIllnessNum;
        SpannableStringBuilder stringBuilder = new SpanUtils().append(String.valueOf(totalCustomNum)).setForegroundColor(getResources().getColor(R.color.tv_red))
                .append("位患者上传了").setForegroundColor(getResources().getColor(R.color.col_AEAEAE)).append(String.valueOf(totalIllnessNum)).setForegroundColor(getResources().getColor(R.color.tv_red))
                .append("份病例,接受了专业的咨询及治疗").setForegroundColor(getResources().getColor(R.color.col_AEAEAE)).create();
        numberUpLoader.setText(stringBuilder);
    }

    @Override
    public void showUserCaseList(List<NewCaseListEntity.PayLoadBean.UserIllnessesBean> userCaseList) {
        if (userCaseList != null) {
            if (userCaseList.size() > 0) {
                ToastUtils.showAtCenter("跳转到病历页面");
            } else {
                ToastUtils.showAtCenter("跳转到病历引导页");
            }
        } else {
            ToastUtils.showAtCenter("跳转到病历引导页");
        }
    }

}
